<template>
  <div class="h-full flex flex-col w-full">
    <slot
      name="buttonlist"
      :fpFlag="
        pageInfo.ycSource == 'FP' ||
        (pageInfo.ycSource == 'PY' &&
          Data?.historyArrList?.find(item => item.pyZycId == pageInfo.pyZycId)?.fpFlag)
      "
    ></slot>
    <div class="scllerView flex-1 w-full">
      <h1 class="mb-2">
        <span class="font-bold text-[18px]">评阅结果：</span> 题目满分：
        <span class="text-red-600 font-bold"> {{ reviewInfo?.tmfz }} </span> 评阅模式：
        <span class="text-red-600 font-bold"> {{ pymsEnum[`pyMs_${reviewInfo?.pyMs}`] }} </span>
      </h1>
      <a-table
        :row-selection="{
          hideDefaultSelections: true,
          hideSelectAll: true,
          selectedRowKeys: Data.checkedList,
          onChange: handelonChanChange,
        }"
        :pagination="false"
        :columns="zgtColumn(pyZtOptions)"
        :data-source="Data.historyArrList?.filter(el => !el.fpFlag) || []"
        :border="true"
        rowKey="pySubmitId"
        style="width: 100%"
        :scroll="{ x: 100 }"
      >
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.key === 'account'">
            <span class="text-[#e52a2a]" :title="`(${record.jsxm})${text}`">
              ({{ record.jsxm }}){{ text }}
            </span>
          </template>
        </template>
      </a-table>
      <div style="margin-top: 10px" v-if="Data.historyArrList?.filter(el => el.fpFlag)?.length">
        <h1 class="mb-2">
          <span class="font-bold text-[18px]">隐式复评结果：</span>
        </h1>
        <a-table
          class="hide_tabs_bar"
          :row-selection="{
            hideDefaultSelections: true,
            hideSelectAll: true,
            selectedRowKeys: Data.checkedList,
            onChange: handelonChanChange,
          }"
          :pagination="false"
          :columns="zgtColumn(pyZtOptions)"
          :data-source="Data.historyArrList?.filter(el => el.fpFlag) || []"
          :border="true"
          rowKey="pySubmitId"
          style="width: 100%"
          :scroll="{ x: 100 }"
        >
          <template #bodyCell="{ column, record, text }">
            <template v-if="column.key === 'account'">
              <span class="text-[#e52a2a]" :title="`(${record.jsxm})${text}`">
                ({{ record.jsxm }}){{ text }}
              </span>
            </template>
          </template>
        </a-table>
      </div>
      <div v-if="Data.errHistoryList?.length">
        <h1 class="mt-5 text-[18px] font-bold">异常记录：</h1>
        <a-checkbox-group v-model:value="Data.checkedList" @change="handelChange">
          <div
            class="score w-full px-[15px] py-2"
            :key="itesub.ycId"
            v-for="itesub in Data.errHistoryList"
          >
            <div class="mb-2 text-[14px] flex items-center">
              <div class="mr-2">
                <span
                  :title="
                    itesub.pySubmitId === '0' ? '该数据无评阅记录' : '勾选该数据后，将显示评阅结果'
                  "
                >
                  <a-checkbox :value="itesub.pySubmitId" :disabled="itesub.pySubmitId === '0'" />
                </span>
                <span
                  class="text-[12px] bg-[#ff5d3f] ml-2 text-white p-1 rounded"
                  v-if="itesub.ycZt !== 'YC_YCL'"
                  title="最新的异常数据"
                >
                  NEW
                </span>
                <span
                  class="text-[12px] ml-2 text-white p-1 rounded bg-green-600"
                  title="当前列表数据的异常数据"
                  v-if="
                    itesub.ycZt !== 'YC_YCL' &&
                    Data.historyArrList.find(item => item.pyZycId === itesub.pyZycId) &&
                    itesub.pyZycId == pageInfo.pyZycId
                  "
                >
                  NOW
                </span>
              </div>
              <div class="flex-1">
                <div class="font-bold mb-1" v-if="itesub.sourcePyAccountName">
                  原评阅教师：({{ itesub.sourcePyAccountName }}){{ itesub.sourcePyAccount }}
                </div>
                <span class="font-bold mr-2 text-red-600">
                  异常状态：{{ ycZtList.find(item => item.value === itesub.ycZt)?.label }}
                </span>
                <span class="font-bold mr-4 text-red-600">
                  异常来源：{{ ycSourceList.find(item => item.value === itesub.ycSource)?.label }}
                </span>
              </div>
            </div>
            <Timeline>
              <Timeline.Item>
                <div calss="text-[14px]">
                  <div>{{ itesub.createTime }}</div>
                  <div class="ml-5">
                    上报人：
                    <span class="font-bold">
                      {{
                        itesub.createAccount
                          ? `(${itesub.createName})${itesub.createAccount}`
                          : '--'
                      }}
                    </span>
                    <br />
                    异常类型：
                    <span class="font-bold"> {{ itesub.ycName }} </span>
                    <br />
                    <div class="flex">
                      异常备注：
                      <span :title="itesub.ycBz" class="font-bold inline-block flex-1 truncate">
                        {{ itesub.ycBz||"--" }}
                      </span>
                    </div>
                  </div>
                </div>
              </Timeline.Item>
              <Timeline.Item v-if="itesub.confirmYcFlag">
                <div calss="text-[14px]">
                  <div>{{ itesub.confirmTime }}</div>
                  <div class="ml-5">
                    处理人：
                    <span class="font-bold">
                      {{
                        itesub.confirmAccount
                          ? `(${itesub.confirmName})${itesub.confirmAccount}`
                          : '--'
                      }}
                    </span>
                    <br />
                    处理结果：
                    <span class="font-bold">
                      {{ ycClfunction[itesub.confirmYcAction] }}
                    </span>
                    <br />
                    <span class="font-bold" v-if="itesub.confirmYcAction === 'CP_POINT'">
                      重评教师： ({{ itesub.confirmName }}){{ itesub.confirmAccount }}
                    </span>
                  </div>
                </div>
              </Timeline.Item>
              <Timeline.Item v-if="itesub.adminActionTime">
                <div calss="text-[14px]">
                  <div>{{ itesub.adminActionTime }}</div>
                  <div class="flex-1">
                    处理人:
                    <span class="font-bold">
                      {{
                        itesub.adminAccount ? `(${itesub.adminName})${itesub.adminAccount}` : '--'
                      }}
                    </span>
                    <br />
                    处理结果：
                    <span class="font-bold">
                      {{ ycClfunction[itesub.adminAction] }}
                    </span>
                    <br />
                    重评教师：
                    <span class="font-bold" v-if="itesub.adminAction === 'CP_POINT'">
                      ({{ itesub.confirmName }}){{ itesub.confirmAccount }}
                    </span>
                  </div>
                </div>
              </Timeline.Item>
            </Timeline>
          </div>
        </a-checkbox-group>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Timeline } from 'ant-design-vue'
import { reactive, ref, watch, onMounted, computed, nextTick } from 'vue'

import { isJdCorrectType } from '/@/views/examination-audit/abnormal-teacher/index'

import { notReview } from '/@/views/exam-info/review-paper/components/index'
import { getDictionaryList } from '/@/views/teacher/home/index'

import { ycClfunction, zgtColumn } from '/@/views/exam-info/review-paper/components/index'
import { useUserStore } from '/@/store/modules/user'
const userStore = useUserStore()
const authorityInfo = computed(() => userStore.getAuthorityItem)
import { pymsEnum } from '/@/views/home/index/index'
import {
  ycZtList,
  ycSourceList,
} from '/@/views/examination-audit/abnormal-examination-paper/components/index'
import {
  getYcRecord,
  getPyZycKgtSubmitData,
  getZycPyRecordListQuery,
  getfullyPyRecord,
  getHistoryPyRecordByYc,
  getDtkTypeByPyZycId,
} from '/@/api/teacher'

import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

const pyZtOptions: any = ref([])

const Data: any = reactive({
  lislsindex: 0,
  errHistoryList: [],
  checkedList: [],
  historyArrList: [],
  zbWeizList: [],
})

const props = defineProps({
  reviewInfo: {
    type: Object,
    default: () => ({}),
  },
  pageInfo: {
    type: Object,
    default: () => ({}),
  },
} as any)

async function getYcListRecord() {
  const { code, data }: any = await getYcRecord({
    pyZycId: props.pageInfo?.ycGroupId ? props.pageInfo.pyZycId : undefined,
    ycGroupId: props.pageInfo?.ycGroupId || undefined,
    pySubmitId: !props.pageInfo?.ycGroupId ? props.pageInfo?.pySubmitId : undefined,
    pyjsFlag: authorityInfo.value?.roleCode == 'PYJS' ? true : false,
  })
  if (code === 200) {
    Data.errHistoryList = data
  }
}
const emit = defineEmits(['historyTagIdlist'])

let valStrue: any = ''
function handelonChanChange(val) {
  Data.checkedList = val
  handelChange(val)
}
async function handelChange(val) {
  emit('historyTagIdlist', {})
  if (Data.checkedList.length > 1 && valStrue.length) {
    Data.checkedList.splice(Data.checkedList.indexOf(valStrue), 1)
  }
  valStrue = Data.checkedList.join(',')
  if (valStrue) {
    let jdFlag = isJdCorrectType(props.pageInfo)
    let item = Data.historyArrList.find(item => item.pySubmitId == valStrue)
    if (!item) {
      let requieFun = jdFlag ? getPyZycKgtSubmitData : getHistoryPyRecordByYc
      const { data, code } = await requieFun(
        jdFlag
          ? {
              pyZycId: props.pageInfo?.pyZycId,
              pyjsFlag: authorityInfo.value?.roleCode == 'PYJS' ? true : false,
              historyFlag: true,
              pySubmitId: valStrue,
            }
          : {
              ycId: Data.errHistoryList.find(el => el.pySubmitId == valStrue)?.ycId,
            }
      )
      if (code == 200) {
        jdFlag ? (item = { pyZycKgtInfoList: data[0].kgtPyRecordList }) : (item = data[0])
      } else {
        return
      }
    }
    nextTick(() => {
      jdFlag ? kgtToolFun(item) : zgtToolFun(item)
    })
  }
}

watch(
  () => props.reviewInfo,
  (nval, oval) => {
    if (!props.pageInfo.pyZycId || nval?.stId == oval?.stId || !nval?.stId) return

    Data.historyArrList = []
    getYcListRecord()
    isJdCorrectType(props.reviewInfo) && isExamPaper()
    getHistoryList()
  },
  { immediate: true, deep: true }
)

// 获取历史打分记录
async function getHistoryList() {
  let jdFlag = isJdCorrectType(props.pageInfo)
  let requieFun = jdFlag ? getZycPyRecordListQuery : getfullyPyRecord
  const { data, code } = await requieFun(
    jdFlag
      ? {
          currentAccountFlag: true,
          stLx: jdFlag ? 'KGT' : 'ZGT', //试题类型(主观/客观)
          kmdm: props.pageInfo.kmdm, //科目代码
          zpDataFlag: props.pageInfo.zpDataFlag, //评阅阶段，正评标志
          stId: props.pageInfo.stId,
        }
      : {
          pyjsFlag: authorityInfo.value?.roleCode == 'PYJS' ? true : false,
          pyZgtId: props.pageInfo?.pyZycId,
        }
  )

  if (code == 200) {
    if (data?.length && !isJdCorrectType(props.pageInfo)) {
      Data.historyArrList =
        data.filter(item => {
          if (item.pyZycId == props.pageInfo.pyZycId) {
            zgtToolFun(item)
            Data.checkedList = [item.pySubmitId]
            valStrue = item.pySubmitId
          }
          return !notReview.includes(item.pyZt)
        }) || []
    } else if (isJdCorrectType(props.pageInfo)) {
      Data.historyArrList = data
      data.forEach(el => {
        if (el.pyZycId == props.pageInfo.pyZycId) {
          Data.checkedList = [el.pySubmitId]
          valStrue = el.pySubmitId
          kgtToolFun(el)
        }
      })
    }
    nextTick(() => {
      linkageScroll()
    })
  }
}

function zgtToolFun(item) {
  let tagsList: any = []
  if (item.pyZycDfdInfoVOList?.length > 0) {
    for (let i = 0; i < item.pyZycDfdInfoVOList.length; i++) {
      let ele = item.pyZycDfdInfoVOList[i]
      let [x, y] = ele.pyLocation.split(',')
      tagsList.push({
        x,
        y,
        value: ele.pyScore,
        stMc: ele.dfdScore,
        pyDtkqtId: ele.pyDtkqtId,
        index: ele.sortNum,
        pyDfdId: ele.pyDfdId,
        dfdId: ele.dfdId,
        account: item.account,
        jsxm: item.jsxm,
      })
    }
  } else {
    if (!item.pyLocation) return
    let [x, y] = item?.pyLocation?.split(',')
    tagsList = [
      {
        x,
        y,
        value: item.pyZdf,
        stMc: item.dfdScore,
        pyDtkqtId: item.pyDtkqtId,
        index: 1,
        pyDfdId: 'totleScole',
        dfdId: '',
        account: item.account,
        jsxm: item.jsxm,
      },
    ]
  }
  emit('historyTagIdlist', {
    tagsList,
  })
}

// 获取切片数据识别信息
async function isExamPaper() {
  let todoList = props.reviewInfo.dtkqtxxVoList.map(el => el.id) || []

  const { code, data } = await getDtkTypeByPyZycId({
    todoList,
  })

  if (code == 200) {
    Data.zbWeizList = data.filter(el => {
      el.xxdwzList = el.xxwz?.slice(1, el.xxwz.length - 1)?.split('),(')
      for (let i = 0; props.reviewInfo?.ckdaInfoList?.length > i; i++) {
        let item = props.reviewInfo.ckdaInfoList[i]
        if (item.stId == el.tmid) {
          let arr = item.ckda.split(',')
          el.ckda = new Array(item.xxsl || 2).fill('0')
          el.xxsl = item.xxsl
          for (let i = 0; i < arr.length; i++) {
            if (props.reviewInfo.tmlx == '判断题') {
              arr[i] === 'true' && (el.ckda[0] = '1')
              arr[i] === 'false' && (el.ckda[1] = '1')
            } else {
              el.ckda[arr[i].charCodeAt(0) - 65] = '1'
            }
          }
          return true
        }
      }
    })
  }
}

/** 客观题处理数据工具 */
function kgtToolFun(el) {
  let reviewShowInfo = {
    jsxm: '',
    account: '',
    pyZdf: 0,
  }
  let pyZycKgtList = el.pyZycKgtInfoList
    .filter(ele => {
      reviewShowInfo.jsxm = ele.jsxm
      reviewShowInfo.account = ele.account
      reviewShowInfo.pyZdf += ele.pyZdf

      for (let i = 0; props?.reviewInfo?.ckdaInfoList?.length > i; i++) {
        let item = props.reviewInfo.ckdaInfoList[i]
        if (ele.stId == item.stId) {
          ele.tmbh = item.tmbh
          ele.tmxh = item.tmxh
          ele.pyDaText =
            ele.pyDa == 'Z'
              ? '未作答'
              : props.reviewInfo.tmlx == '判断题'
              ? ele.pyDa == 'false'
                ? '×'
                : ele.pyDa == 'true'
                ? '√'
                : '√,×'
              : ele.pyDa
          break
        }
      }
      return !Data.zbWeizList.find(element => {
        if (ele.stId == element.tmid) {
          element.pyDa = ele.pyDa
          let arr = element.pyDa.split(',')
          element.sbdjgList = new Array(element.xxsl || 2).fill('0')
          for (let i = 0; i < arr.length; i++) {
            if (props.reviewInfo.tmlx == '判断题') {
              arr[i] === 'true' && (element.sbdjgList[0] = '1')
              arr[i] === 'false' && (element.sbdjgList[1] = '1')
            } else {
              element.sbdjgList[arr[i].charCodeAt(0) - 65] = '1'
            }
          }
          return true
        }
      })
    })
    .sort((a, b) => a.tmxh - b.tmxh)

  emit('historyTagIdlist', {
    pyZycKgtList,
    dtkType: Data.zbWeizList,
    reviewShowInfo,
  })
}

/**
 * tab联动
 */
function linkageScroll() {
  let antTableContent = document.getElementsByClassName('ant-table-content')
  if (antTableContent.length <= 1) return
  antTableContent[0]?.addEventListener('scroll', () => {
    if (antTableContent[1] && antTableContent[0]) {
      antTableContent[1].scrollLeft = antTableContent[0].scrollLeft
    }
  })
  antTableContent[1]?.addEventListener('scroll', () => {
    if (antTableContent[1] && antTableContent[0]) {
      antTableContent[0].scrollLeft = antTableContent[1].scrollLeft
    }
  })
}

onMounted(async () => {
  await getDictionaryList('pyListZtCode', pyZtOptions)
})

defineExpose({
  getYcListRecord,
})
</script>

<style lang="less" scoped>
.scllerView {
  width: 100%;
  overflow-y: auto;
  padding: 15px;

  .hide_tabs_bar {
    ::v-deep(.ant-table-thead) {
      display: none;
    }
  }

  .ant-checkbox-group {
    width: 100%;
  }

  .score {
    .header {
      display: flex;
      display: -webkit-flex;
      display: -ms-flexbox;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      color: #0f0f0f9c;
      font-size: 16px;
      margin-bottom: 10px;
      cursor: pointer;

      .number {
        font-size: 12px;
        background-color: #136cc4;
        color: #fff;
        padding: 0 5px;
        border-radius: 5px;
        margin-right: 10px;
      }

      .tagSty {
        font-size: 12px;
        background-color: #ff5d3f;
        color: #fff;
        padding: 0 5px;
        border-radius: 5px;
        margin-right: 10px;
      }
    }

    .table {
      border: 1px #dfd8d8 solid;
      width: 600px;
      .table-header {
        background: #b1abab;
        padding: 8px 12px;
        font-size: 14px;
        font-weight: 600;
      }
    }
  }
}
</style>
